package com.googlecode.imule.apps;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.Scanner;

import javax.media.MediaLocator;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

import com.apple.dnssd.DNSSDException;
import com.googlecode.imule.apps.util.ListenerX;
import com.googlecode.imule.data.Action;
import com.googlecode.imule.data.Parse;
import com.googlecode.imule.data.UDPCommunicationX;
import com.googlecode.imule.discovery.Contact;
import com.googlecode.imule.discovery.DiscoveryServiceX;
import com.googlecode.imule.media.IStream;
import com.googlecode.imule.redundant.Components;

/**
 * A component that combines the discovery, communication modules of
 * the imule platform.
 * 
 * @author Neil Cowzer
 */
public class Y extends X{
	IStream streamer;
	
	public String streamingTO;
	
	public Y(String name) throws SocketException, DNSSDException {
		super(name);
	}
	
	@Override
	public void setOn(boolean status) {
		if (status){
			if (streamer != null)
				streamer.stop();
			Contact contact = discovery.getContacts().getContact(streamingTO);
			System.out.println("streaming to: " + contact.getIpAddress().toString());
			
			String ip = contact.getIpAddress().toString();
			ip = ip.substring(1, ip.length());
			
			System.out.println(ip);
			
			streamer = new IStream(
					new MediaLocator("file:/C:/Documents and Settings/Neil/My Documents/College/Distributed Systems/Project/imule/resources/01.wav"),
							ip, "9000");
			
			streamer.start();
		} else {
			streamer.stop();
			System.out.println("stopping...");
		}
	}
	
	@Override
	public void execute(String xml) {
		Action action = null;

		try {
			action = Parse.action(xml);
			
			if (action.getName().equalsIgnoreCase("setOn")){
				if (action.getArguments().get(0).getValue().equalsIgnoreCase("true")){
					streamingTO = action.getId();
					setOn(true);
				} else
					setOn(false);
			}
			
		} catch (IOException e){
		} catch (SAXException e){}
	}
	
	public static void main(String[] args) throws SocketException, DNSSDException {
		Y test = new Y("streamer");
	}
}
